<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入账号" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入昵称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="住址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入住址" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="queryParams.description" placeholder="请输入简介" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="套餐" prop="packId">
        <el-input v-model="queryParams.packId" placeholder="请输入套餐id" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="套餐类型" prop="packId" style="width: 250px;">
        <el-select v-model="queryParams.packId" placeholder="请选择所属套餐类型" @change="handleQuery" clearable>
          <el-option v-for="item in packType" :key="item.packId" :label="item.packName" :value="item.packId" />
        </el-select>
      </el-form-item>

      <el-form-item label="权限字符" prop="role">
        <el-input v-model="queryParams.role" placeholder="请输入权限字符" clearable @keyup.enter="handleQuery" />
      </el-form-item>


      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['users:users:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['users:users:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['users:users:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['users:users:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="账号" align="center" prop="username" show-overflow-tooltip />
      <el-table-column label="昵称" align="center" prop="nickname" show-overflow-tooltip />
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="住址" align="center" prop="address" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.address && scope.row.address.trim() !== ''">
            {{ scope.row.address }}
          </span>
          <span v-else>
            无
          </span>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phone" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.phone && scope.row.phone.trim() !== ''">
            {{ scope.row.phone }}
          </span>
          <span v-else>
            无
          </span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="description" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.description && scope.row.description.trim() !== ''">
            {{ scope.row.description }}
          </span>
          <span v-else>
            无
          </span>
        </template>
      </el-table-column>
      <el-table-column label="套餐id" align="center" prop="packId" />

      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="sys_user_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="权限" align="center" prop="role" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['users:users:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['users:users:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改用户信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" />
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="form.description" placeholder="请输入简介" />
        </el-form-item>

        <el-form-item label="充值套餐" prop="packId">
          <el-select v-model="form.packId" placeholder="请选择充值套餐" clearable>
            <el-option v-for="item in packType" :key="item.packId" :label="item.packName"
              :value="item.packId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="权限" prop="role">
          <el-select v-model="form.role" placeholder="请选择权限" clearable style="width: 100%">
            <el-option v-for="item in roleStrOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_user_status" :key="dict.value" :value="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="!form.username || !form.role || !form.packId
            || !form.status">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Users">
import { listUsers, getUsers, delUsers, addUsers, updateUsers } from "@/api/users/users"
import { listTpackage } from "../../../api/tpackage/tpackage"
import { parseTime } from "../../../utils/ruoyi.js";

const roleStrOptions = ref([
  { label: 'super_admin', value: 'super_admin' },
  { label: 'admin', value: 'admin' },
  { label: 'common', value: 'common' }
]);

const { proxy } = getCurrentInstance()
const packType = ref([])
//日期范围
const dateRange = ref([])
const { sys_user_status } = proxy.useDict("sys_user_status")
const usersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    username: null,
    password: null,
    nickname: null,
    avatar: null,
    address: null,
    phone: null,
    description: null,
    packId: null,
    status: null,
    role: null,
    beginTime: null,
    endTime: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)


onMounted(() => {
  listTpackage().then(res => {
    packType.value = res.rows
    packType.value = packType.value.filter(item => item.status === '0'); // 仅保留status=0的项
    console.log(packType.value);
  })
})

/** 查询用户信息管理列表 */
function getList() {
  loading.value = true
  listUsers({
    ...queryParams.value,
    // 明确传递日期范围参数
    beginTime: queryParams.value.beginTime,
    endTime: queryParams.value.endTime
  }).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    username: null,
    password: null,
    nickname: null,
    avatar: null,
    address: null,
    phone: null,
    description: null,
    packId: null,
    status: null,
    role: 'common'
  }
  proxy.resetForm("usersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")

  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户信息管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _userId = row.userId || ids.value
  getUsers(_userId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改用户信息管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usersRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != null) {
        updateUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除用户信息管理编号为"' + _userIds + '"的数据项？').then(function () {
    return delUsers(_userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('users/users/export', {
    ...queryParams.value
  }, `users_${new Date().getTime()}.xlsx`)
}

getList()
</script>
